package com.foreveross.action;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.foreveross.service.LogService;
import com.foreveross.service.SysMenuManagerService;
import com.foreveross.service.SysRoleManagerService;
import com.foreveross.service.SysRoleMenuManagerService;
import com.foreveross.service.SysUserService;
import com.foreveross.util.AuthUtil;
import com.foreveross.vo.HouseUser;
import com.foreveross.vo.SysMenu;
import com.foreveross.vo.SysRole;
import com.foreveross.vo.SysUser;
import com.foreveross.vo.common.PageVo;
import com.foreveross.vo.common.ResultVo;
import com.foreveross.common.CommonUtil;
import com.foreveross.common.Constants;

/**
 * 后台用户权限 管理
 * 
 * @author wm
 * 
 */
@Controller
@RequestMapping(value = "/sysUserAuthorityManagerContraller")
public class SysUserAuthorityManagerContraller extends BaseCostroller {
	private Logger log = Logger
			.getLogger(SysUserAuthorityManagerContraller.class);

	@Resource
	private SysRoleManagerService sysRoleManagerService;
	@Resource
	private SysMenuManagerService sysMenuManagerService;
	@Resource
	private SysRoleMenuManagerService sysRoleMenuManagerService;

	@Resource
	private SysUserService userService;

	@Resource
	private LogService logService;

	/**
	 * 系统角色查询
	 * 
	 * @param request
	 * @param response
	 * @param type
	 * @param typeName
	 * @param codeDesc
	 * @param OnePageCount
	 * @param currentPage
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getSysRole")
	public void getSysRole(HttpServletRequest request,
			HttpServletResponse response, String name, String rows, String page) {
		ResultVo resultVo = new ResultVo();
		try {
			int countRecord = (int) sysRoleManagerService
					.getSysRoleListCount(name);
			PageVo<SysRole> pageObj = new PageVo<SysRole>(page, countRecord,
					rows);
			pageObj.setRows(sysRoleManagerService.getSysRoleList(name,
					pageObj.getpageIndex(), pageObj.getpageSize()));

			resultVo.setData(pageObj);
			resultVo.setSuccess(true);
			log.info("系统角色查询 查看成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统角色查询 查看失败");
			log.error("系统角色查询 查看失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 系统角色更新
	 * 
	 * @param request
	 * @param response
	 * @param sysRole
	 * @param updateType
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/updateSysRole")
	public void updateSysRole(HttpServletRequest request,
			HttpServletResponse response, SysRole sysRole, String updateType) {
		ResultVo resultVo = new ResultVo();
		try {
			if (Constants.UPDATE_ADD.equals(updateType))
				sysRole.setCreationTime(new Date());
			else
				sysRole.setUpdateTime(new Date());
			sysRoleManagerService.saveOrUpdate(sysRole, updateType,
					sysRole.getId());
			resultVo.setSuccess(true);
			logService.saveLog(
					this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND,
					updateType.equals(Constants.UPDATE_ADD) ? Constants.LOG_ADD
							: Constants.LOG_UPDATE,
					"角色" + Constants.getUpdateType(updateType),
					AuthUtil.getUserid(request),
					Constants.getUpdateType(updateType) + "角色["
							+ sysRole.toString() + "]");
			log.info("系统角色 " + updateType + "成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统角色 " + updateType + "失败");
			log.error("系统角色 " + updateType + "失败!", e);
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 系统角色删除
	 * 
	 * @param request
	 * @param response
	 * @param ids
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/deleteSysRoleList")
	public void deleteSysRoleList(HttpServletRequest request,
			HttpServletResponse response, String ids) {
		ResultVo resultVo = new ResultVo();
		try {
			sysRoleManagerService.deleteSysRole(ids);
			resultVo.setSuccess(true);
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_DEL,
					"角色删除", AuthUtil.getUserid(request), "角色[" + ids + "]");
			log.info("系统角色 删除成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统角色 删除失败");
			log.info("系统角色 删除失败!");
			e.printStackTrace();
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 系统菜单查询
	 * 
	 * @param request
	 * @param response
	 * @param type
	 * @param typeName
	 * @param codeDesc
	 * @param OnePageCount
	 * @param currentPage
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getSysMenu")
	public void getSysMenu(HttpServletRequest request,
			HttpServletResponse response, String name, String rows, String page) {
		ResultVo resultVo = new ResultVo();
		try {
			int countRecord = (int) sysMenuManagerService
					.getSysMenuListCount(name);
			PageVo<SysMenu> pageObj = new PageVo<SysMenu>(page, countRecord,
					rows);
			pageObj.setRows(sysMenuManagerService.getSysMenuList(name,
					pageObj.getpageIndex(), pageObj.getpageSize()));

			resultVo.setData(pageObj);
			resultVo.setSuccess(true);
			log.info("系统菜单查询 查看成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统菜单查询 查看失败");
			log.error("系统菜单查询 查看失败!", e);
		}

		List list = Arrays.asList("parent");
		CommonUtil.PrintWriterResultWithJSON(response, resultVo, list);
		// CommonUtil.PrintWriterResultVoWithJSONGson(response, resultVo);
	}

	/**
	 * 系统菜单更新
	 * 
	 * @param request
	 * @param response
	 * @param sysMenu
	 * @param updateType
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/updateSysMenu")
	public void updateSysMenu(HttpServletRequest request,
			HttpServletResponse response, SysMenu sysMenu, String updateType) {
		ResultVo resultVo = new ResultVo();
		try {
			if (Constants.UPDATE_ADD.equals(updateType))
				sysMenu.setCreationTime(new Date());
			else
				sysMenu.setUpdateTime(new Date());
			sysMenuManagerService.saveOrUpdate(sysMenu, updateType,
					sysMenu.getId());
			resultVo.setSuccess(true);
			logService.saveLog(
					this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND,
					Constants.LOG_ADD,
					"系统菜单" + Constants.getUpdateType(updateType),
					AuthUtil.getUserid(request),
					Constants.getUpdateType(updateType) + "系统菜单["
							+ sysMenu.toString() + "]");
			log.info("系统菜单 " + updateType + "成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统菜单 " + updateType + "失败");
			log.error("系统菜单 " + updateType + "失败!", e);
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 系统菜单删除
	 * 
	 * @param request
	 * @param response
	 * @param ids
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/deleteSysMenuList")
	public void deleteSysMenuList(HttpServletRequest request,
			HttpServletResponse response, String ids) {
		ResultVo resultVo = new ResultVo();
		try {
			sysMenuManagerService.deleteSysMenu(ids);
			resultVo.setSuccess(true);
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_ADD,
					"系统菜单删除", AuthUtil.getUserid(request), "系统菜单[" + ids + "]");
			log.info("系统菜单 删除成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统菜单 删除失败");
			log.info("系统菜单 删除失败!");
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 系统角色菜单 查看
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 *            角色ID
	 * @param updateType
	 *            查看：WATCH ,修改: EDIT
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getSysRoleMenu")
	public void getSysRoleMenu(HttpServletRequest request,
			HttpServletResponse response, String roleId, String updateType) {
		ResultVo resultVo = new ResultVo();
		try {

			SysRole sysRole = (SysRole) sysRoleManagerService.getObjectById(
					SysRole.class, roleId);
			List<SysMenu> menuList = sysMenuManagerService.getSysRoleMenu(
					roleId, updateType);
			sysRole.setSysMenus(menuList);

			resultVo.setData(sysRole);
			resultVo.setSuccess(true);
			log.info("系统角色菜单查询 查看成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统角色菜单查询 查看失败");
			log.error("系统角色菜单查询 查看失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 角色菜单授权
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 *            角色ID
	 * @param menuIds
	 *            菜单IDS
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/updateSysRoleMenu")
	public void updateSysRoleMenu(HttpServletRequest request,
			HttpServletResponse response, String roleId, String menuIds) {
		ResultVo resultVo = new ResultVo();
		try {
			sysRoleMenuManagerService.saveOrUpdate(roleId, menuIds);
			resultVo.setSuccess(true);
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_ADD,
					"角色菜单授权", AuthUtil.getUserid(request), "角色[" + roleId
							+ "]授权菜单[" + menuIds + "]");
			log.info("系统角色菜单授权 成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统角色菜单授权 失败");
			log.error("系统角色菜单授权 失败!", e);
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	@RequestMapping(method = RequestMethod.POST, value = "/findUserList")
	public void findUserList(HttpServletRequest request,
			HttpServletResponse response, String rows, String page,
			String name, String account) {
		ResultVo resultVo = new ResultVo();
		try {
			int countRecord = (int) userService.getUserListCount(name, account);
			PageVo<SysUser> pageObj = new PageVo<SysUser>(page, countRecord,
					rows);
			pageObj.setRows(userService.findUserList(name, account,
					pageObj.getpageIndex(), pageObj.getpageSize()));
			resultVo.setData(pageObj);
			resultVo.setSuccess(true);
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统用户 查看失败");
			log.error("系统用户 查看失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 用户绑定角色
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/userBindRole")
	public void userBindRole(HttpServletRequest request,
			HttpServletResponse response, String sysUserId, String roleIds) {
		ResultVo resultVo = new ResultVo();
		try {
			userService.saveUserBindRole(sysUserId, roleIds);
			resultVo.setSuccess(true);
			log.info("用户绑定角色 成功!");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("用户绑定角色  失败");
			log.error("用户绑定角色  失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 角色绑定菜单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/roleBindMemu")
	public void roleBindMemu(HttpServletRequest request,
			HttpServletResponse response, String roleId, String memuIds) {
		ResultVo resultVo = new ResultVo();
		try {
			userService.roleBindMemu(roleId, memuIds);
			resultVo.setSuccess(true);
			log.info("用户绑定角色 成功!");
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_ADD,
					"用户绑定角色", AuthUtil.getUserid(request), "添加用户绑定角色[" + roleId
							+ "]");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("用户绑定角色  失败");
			log.error("用户绑定角色  失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	@RequestMapping(method = RequestMethod.POST, value = "/findroleHrHouse")
	public void findroleHrHouse(HttpServletRequest request,
			HttpServletResponse response, String roleId) {
		JSONArray array = new JSONArray();
		try {
			array = sysMenuManagerService.findroleHrHouse(roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommonUtil.PrintJSONSTR(response, array.toString());

	}

	@RequestMapping(method = RequestMethod.POST, value = "/roleBindHrHouse")
	public void roleBindHrHouse(HttpServletRequest request,
			HttpServletResponse response, String roleId, String hrHouseIds) {
		ResultVo resultVo = new ResultVo();
		try {
			userService.roleBindHrHouse(roleId, hrHouseIds);
			resultVo.setSuccess(true);
			log.info("用户绑定角色 成功!");
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_ADD,
					"用户绑定角色", AuthUtil.getUserid(request), "添加用户绑定角色[" + roleId
							+ "]");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("用户绑定角色  失败");
			log.error("用户绑定角色  失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 添加更加用户
	 * 
	 * @param request
	 * @param response
	 * @param user
	 * @param updateType
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/addOrupdateUser")
	public void addOrupdateUser(HttpServletRequest request,
			HttpServletResponse response, SysUser user, String updateType) {
		ResultVo resultVo = new ResultVo();
		try {
			if (Constants.UPDATE_ADD.equals(updateType)) {
				// user.setId(CommonUtil.getUUID());
				user.setCreateTime(new java.sql.Timestamp(new java.util.Date()
						.getTime()));

				userService.saveOrUpdate(user, Constants.UPDATE_ADD,
						user.getId());
				logService.saveLog(this.getUserIP(request),
						Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_ADD,
						"添加用户", AuthUtil.getUserid(request),
						"添加用户[" + user.toString() + "]");
			} else if (Constants.UPDATE_EDIT.equals(updateType)) {
				user.setUpdateTime(new java.util.Date());

				userService.saveOrUpdate(user, Constants.UPDATE_EDIT,
						user.getId());
				logService.saveLog(this.getUserIP(request),
						Constants.OPERATE_TYPE_BACKGROUND,
						Constants.LOG_UPDATE, "更新用户",
						AuthUtil.getUserid(request), "更新用户[" + user.toString()
								+ "]");
			}
			resultVo.setSuccess(true);
			log.info("系统用户 " + updateType + "成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统用户  " + updateType + "失败");
			log.error("系统用户  " + updateType + "失败!", e);
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 查看个人信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findUser")
	public void findUser(HttpServletRequest request,
			HttpServletResponse response, String id) {
		ResultVo resultVo = new ResultVo();
		try {
			SysUser sysUser = (SysUser) this.findObject(SysUser.class, id);
			resultVo.setSuccess(true);
			resultVo.setData(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("查看用户信息失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 查看个人信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findRole")
	public void findRole(HttpServletRequest request,
			HttpServletResponse response, String id) {
		ResultVo resultVo = new ResultVo();
		try {
			SysRole sysUser = (SysRole) this.findObject(SysRole.class, id);
			resultVo.setSuccess(true);
			resultVo.setData(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("查看角色信息失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 查看个人信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findSysMenu")
	public void findSysMenu(HttpServletRequest request,
			HttpServletResponse response, String id) {
		ResultVo resultVo = new ResultVo();
		try {
			SysMenu sysMenu = (SysMenu) this.findObject(SysMenu.class, id);
			resultVo.setSuccess(true);
			resultVo.setData(sysMenu);
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("查看角色信息失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 删除用户列表
	 * 
	 * @param request
	 * @param response
	 * @param userIds
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/deleteUserList")
	public void deleteUserList(HttpServletRequest request,
			HttpServletResponse response, String ids) {
		ResultVo resultVo = new ResultVo();
		try {
			userService.deleteUserList(ids);
			resultVo.setSuccess(true);
			log.info("系统用户  删除成功!");
			logService.saveLog(this.getUserIP(request),
					Constants.OPERATE_TYPE_BACKGROUND, Constants.LOG_DEL,
					"删除用户", AuthUtil.getUserid(request), "删除用户ID[" + ids + "]");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("系统用户  删除失败");
			log.info("系统用户  删除失败!");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	@RequestMapping(method = RequestMethod.POST, value = "/getUserRoleList")
	public void getUserRoleList(HttpServletRequest request,
			HttpServletResponse response, String sysUserId) {
		JSONArray array = new JSONArray();
		try {
			array = sysRoleManagerService.getUserRoleList(sysUserId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommonUtil.PrintJSONSTR(response, array.toString());
	}

	@RequestMapping(method = RequestMethod.POST, value = "/getMenuList")
	public void getMenuList(HttpServletRequest request,
			HttpServletResponse response, String userId) {
		JSONArray array = new JSONArray();
		try {
			String roleId = userService.getUserRole(userId);
			if (roleId != null && !"".equals(roleId))
				array = sysMenuManagerService.getMenuList("1", roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommonUtil.PrintJSONSTR(response, array.toString());
	}

	/**
	 * 获取登陆用户的姓名
	 * 
	 * @param request
	 * @param response
	 * @param userId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findLoginName")
	public void findLoginName(HttpServletRequest request,
			HttpServletResponse response, String userId) {
		ResultVo resultVo = new ResultVo();
		SysUser user = (SysUser) request.getSession().getAttribute(userId);
		if (user != null) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("userName", user.getName());
			resultVo.setData(map);
			resultVo.setSuccess(true);
		} else {
			resultVo.setSuccess(false);
			resultVo.setMessage("该用户还未登陆");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 获取菜单树同时自动选中父亲节点
	 * 
	 * @param request
	 * @param response
	 * @param parentId
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/fatherMenuList")
	public void fatherMenuList(HttpServletRequest request,
			HttpServletResponse response, String parentId) {
		JSONArray array = new JSONArray();
		try {
			array = sysMenuManagerService.fatherMenuList("1", parentId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommonUtil.PrintJSONSTR(response, array.toString());
	}

	/**
	 * 查看角色对应菜单
	 * 
	 * @param request
	 * @param response
	 * @param roleId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findRoleMenuList")
	public void findRoleMenuList(HttpServletRequest request,
			HttpServletResponse response, String roleId) {
		JSONArray array = new JSONArray();
		try {
			array = sysMenuManagerService.findRoleMenuList("1", roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommonUtil.PrintJSONSTR(response, array.toString());
	}

}
